package com.wangcang.widgetlibrary.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wangcang.widgetlibrary.R;
import com.wangcang.widgetlibrary.bean.TagBean;

import java.util.List;

/**
 * Created by zhangxutong .
 * Date: 16/08/28
 */

public class TagAdapter extends RecyclerView.Adapter<TagAdapter.ViewHolder> {
    private List<TagBean> mList;

	public interface OnItemClickListener{
		void onItemClick(TagBean tagBean, int position);
	}

	private OnItemClickListener mOnItemClickListener;

	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		this.mOnItemClickListener = onItemClickListener;
	}

    public TagAdapter(List<TagBean> list) {
        this.mList = list;
    }

    @Override
    public TagAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false));
    }

	private int mLastSelectedPosition = -1;

    @Override
    public void onBindViewHolder(final TagAdapter.ViewHolder holder, final int position) {
        final TagBean tagBean = mList.get(position);
		holder.tv.setText(tagBean.getTag());
		holder.ll.setSelected(tagBean.isSelected());
		if (tagBean.isSelected()) {
			mLastSelectedPosition = position;
		}
		if (tagBean.getItemCount() > 0) {
			holder.tvCount.setVisibility(View.VISIBLE);
			holder.tvCount.setText("" + tagBean.getItemCount());
		} else {
			holder.tvCount.setVisibility(View.INVISIBLE);
		}
		holder.itemView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				restore();
				if (mOnItemClickListener != null) {
					mOnItemClickListener.onItemClick(tagBean, position);
				}
			}
		});
    }

	public void restore() {
		if (mLastSelectedPosition > -1) {
			mList.get(mLastSelectedPosition).setSelected(false);
		}
	}

	@Override
    public int getItemCount() {
        return mList != null ? mList.size() : 0;
    }

	static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv;
		LinearLayout ll;
		TextView tvCount;

        public ViewHolder(View itemView) {
            super(itemView);
            tv = (TextView) itemView.findViewById(R.id.tv);
			ll = (LinearLayout) itemView.findViewById(R.id.ll);
			tvCount = (TextView) itemView.findViewById(R.id.tv_count);
		}
    }
}
